package com.zzu.base.controller.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzu.base.common.pojo.ResultResponse;
import com.zzu.base.controller.role.vo.RoleGetRespVO;
import com.zzu.base.controller.user.vo.UserGetRespVO;
import com.zzu.base.controller.user.vo.UserPageReqVO;
import com.zzu.base.controller.user.vo.UserUpdateReqVO;
import com.zzu.base.entity.UserDO;
import com.zzu.base.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Tag(name = "用户")
@PreAuthorize("hasPermission(null,'restricted_use')")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private PasswordEncoder passwordEncoder;

    private static final CopyOptions COPY_OPTIONS = CopyOptions.create()
            .setIgnoreNullValue(false)
            .setIgnoreError(true);

    @Operation(method = "用户角色添加")
    @GetMapping("/role/add")
    @PreAuthorize("hasPermission(null,'permit_all')")
    public ResultResponse<Boolean> userRoleAdd(@Positive Long userId, @Positive Long roleId) {
        return ResultResponse.success(userService.addUserRole(userId, roleId));
    }

    @Operation(method = "用户角色移除")
    @GetMapping("/role/remove")
    @PreAuthorize("hasPermission(null,'permit_all')")
    public ResultResponse<Boolean> userRoleRemove(@Positive Long userId, @Positive Long roleId){
        return ResultResponse.success(userService.removeUserRole(userId, roleId));
    }

    @Operation(method = "用户角色列表")
    @GetMapping("/role/list")
    public ResultResponse<List<RoleGetRespVO>> userRoleList(@Positive Long id){
        return ResultResponse.success(userService.getRolesByUserId(id).stream()
                .map(roleDO -> BeanUtil.toBean(roleDO, RoleGetRespVO.class, COPY_OPTIONS))
                .collect(Collectors.toList()));
    }

    @Operation(method = "用户注销")
    @GetMapping("/remove")
    public ResultResponse<Boolean> userRemove(@Positive Long id) {
        return ResultResponse.success(userService.removeUser(id));
    }

    @Operation(method = "用户列表")
    @GetMapping("/list")
    public ResultResponse<List<UserGetRespVO>> userList() {
        List<UserDO> userList = userService.list();
        return ResultResponse.success(userList.stream()
                .map(userDO -> BeanUtil.toBean(userDO, UserGetRespVO.class, COPY_OPTIONS))
                .collect(Collectors.toList()));
    }

    @Operation(method = "用户获取")
    @GetMapping("/get")
    public ResultResponse<UserGetRespVO> userGet(@Positive Long id) {
        UserDO userDO = userService.getById(id);
        return ResultResponse.success(BeanUtil.toBean(userDO, UserGetRespVO.class, COPY_OPTIONS));
    }

    @Operation(method = "用户修改")
    @PostMapping("/update")
    @PreAuthorize("hasPermission(null,'permit_all')")
    public ResultResponse<Boolean> userUpdate(@Valid @RequestBody UserUpdateReqVO userUpdateReqVO) {
        UserDO userDO = BeanUtil.toBean(userUpdateReqVO, UserDO.class, COPY_OPTIONS);
        // 单独处理密码加密
        userDO.setPassword(passwordEncoder.encode(userUpdateReqVO.getPassword()));
        return ResultResponse.success(userService.update(userDO));
    }

    @Operation(method = "用户分页")
    @PostMapping("/page")
    public ResultResponse<IPage<UserGetRespVO>> userPage(@Valid @RequestBody UserPageReqVO userPageReqVO) {
        IPage<UserDO> userPage = userService.getUserPage(userPageReqVO);

        IPage<UserGetRespVO> resultPage = new Page<>();
        BeanUtil.copyProperties(userPage, resultPage, COPY_OPTIONS);
        List<UserGetRespVO> records = userPage.getRecords().stream()
                .map(userDO -> BeanUtil.toBean(userDO, UserGetRespVO.class, COPY_OPTIONS))
                .collect(Collectors.toList());
        resultPage.setRecords(records);

        return ResultResponse.success(resultPage);
    }

    @Operation(method = "退出登录")
    @GetMapping("/logout")
    public ResultResponse<Boolean> userLogout() {
        return ResultResponse.success(true);
    }
}
